package com.stu.controller.admin;

import com.stu.context.BaseContext;
import com.stu.pojo.Login;
import com.stu.result.Result;
import com.stu.serive.LoginService;

import com.stu.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Result login(@RequestBody Login login){

        Login e = loginService.login(login);
        log.info("员工登录：{}", e);
        //登录成功生成令牌，返回令牌
        if(e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("empId",e.getId());
            claims.put("name",e.getName());
            claims.put("username", e.getUsername());
            claims.put("role", 1);
            log.info("com.stu.controller.admin-claims:{}",claims);
            BaseContext.setRole(1L);
            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息

            return Result.success(jwt);
        }
        //生成失败，返回错误信息
        return Result.error("用户名或密码错误");
    }
}
